#include "widget.h"
#include "ui_widget.h"
/************登录注册界面******************************/
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //1.连接服务器

    // 创建 QTcpSocket 对象
    socket = new QTcpSocket(this);

    // 连接到本地服务端
    socket->connectToHost("127.0.0.1", 1234);

    // 连接连接成功的信号与槽函数
    connect(socket, &QTcpSocket::connected, [this]() {
        // 连接成功, 发送账号和密码
        qDebug() << "Connected to the server!";
        QMessageBox::information(this, "连接提示", "连接服务器成功");
    });

    // 连接失败，警告提示框
    connect(socket, &QTcpSocket::disconnected, this, [=]() {
        QMessageBox::warning(this, "连接提示", "连接断开！");
        qDebug() << "Failed to connect to the server!";
    });

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_loginBtn_clicked()
{

    QString username = ui->userLine->text();
    QString password = ui->passLine->text();
    if (username.isEmpty()) {
        QMessageBox::warning(nullptr, "提示", "用户名不能为空");
        return;
    }
    if (password.isEmpty()) {
        QMessageBox::warning(nullptr, "提示", "密码不能为空");
        return;
    }


    QString action = "LOGIN";
    QDataStream stream(socket);

    // 发送消息
    stream << action << username << password;

    // 接收服务器的回应
    bool response;
    if (socket->waitForReadyRead()) {
        stream >> response;
        qDebug() << "row 54 response is" << response;
    }
    if (response) { //登录成功
        QMessageBox::information(this, "登录成功", "登录成功！");
        this->hide();

        Home *h = new Home(username, socket);
        h->show();
    }else { // 登录失败
        QMessageBox::warning(this, "登录失败", "用户名或密码错误！");
    }
}

void Widget::on_registerBtn_clicked()
{
    QString username = ui->userLine->text();
    QString password = ui->passLine->text();
    if (username.isEmpty()) {
        QMessageBox::warning(nullptr, "提示", "用户名不能为空");
        return;
    }
    if (password.isEmpty()) {
        QMessageBox::warning(nullptr, "提示", "密码不能为空");
        return;
    }
    QString action = "REGISTER";
    QDataStream stream(socket);

    // 发送消息
    stream << action << username << password;

    // 接收服务器的回应
    bool response;
    if (socket->waitForReadyRead()) {
        stream >> response;
        qDebug() << "row 54 response is" << response;
    }

    if (response) { //注册成功
        QMessageBox::information(this, "注册成功", "注册成功！");

    }else { // 注册失败
        QMessageBox::warning(this, "注册失败", "注册失败！");
    }
}

void Widget::on_changeBtn_clicked()
{
    Change *c = new Change(socket); //创建修改密码的界面
    c->show();
    this->hide();
    connect(c, &Change::goBack, this, [this]{
        this->show();
    });
}
